var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer'); 
var Article = require('./Article');

var app = express();

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer({ dest: 'public/upload/'}).array('img'));
app.use(express.static('./'));

const DOMAIN = 'http://localhost:3008/';

app.all("*",function(req,res,next){

    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");//预检请求使用
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");//预检请求使用
    
    next()

})

//restfull api
app.get('/article',function(req,res){


    Article.find({},function(err,result){

        if(err){

        }else{
            console.log(result);
            res.send(result);
        }
    })
})


app.post('/article',function(req,res){

    console.log('body:',req.body)
    var content = req.body.content;
    console.log(content);

    var filepath = req.files[0].path;
    filepath  = DOMAIN + filepath;

    var article = new Article({
        author:"abc",
        content:content,
        author_avatar:"",
        create_time:new Date(),
        img:filepath,
        thumbs:0,
        comment:0,
        share:0
    })

    article.save(function(err,result){

        if(err){
            console.log(err)
        }else{
            res.redirect('http://localhost:3000/#/index/home');
        }

    })

})

app.get('/test',function(req,res){
    console.log('test...')
})

app.post('/upload',function(req,res){

    console.log('upload...')
    console.log(req.body);
    console.log(req.files)

    res.redirect('http://localhost:3000/#/index/home');

})



app.listen(3008,function(){
    console.log('server start.....')
})